﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfSnqkGasAnalysis.IData;
using WpfSnqkGasAnalysis.Model;

namespace WpfSnqkGasAnalysis.IData_impl
{
    /// <summary>
    /// 水露点。数据接口实现
    /// </summary>
    /// 创建时间：2022-12-23 11:05:13。作者：王浩力
    public class Water_pointDAL_impl : BaseDAL, IWater_pointDAL
    {
        public IResult Add(Water_point water_Point)
        {
            Snowflake snowflake = new Snowflake(1, 1);
            string sql = @$" INSERT INTO water_point (
                            Id,
                            Report_no,
                            Client,
                            Analyst,
                            FluTemperature,
                            WellAndWellNo,
                            AirSource,
                            Analytime,
                            AnalyUnit,
                            TestLocation,
                            AmbientTemperature,
                            Createtime,
                            StepCurrent,
                            InputUserId,
                            InputUserRealName                   
                        )
                        VALUES (
                            {water_Point.Id},
                            $Report_no,
                            $Client,
                            $Analyst,
                            $FluTemperature,
                            $WellAndWellNo,
                            $AirSource,
                            $Analytime,
                            $AnalyUnit,
                            $TestLocation,
                            $AmbientTemperature,
                            $Createtime,
                            $StepCurrent,
                            $InputUserId,
                            $InputUserRealName                
                        );  ";
            Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
            keyValuePairs.Add("$Report_no", water_Point.Report_no);
            keyValuePairs.Add("$Client", water_Point.Client);
            keyValuePairs.Add("$Analyst", water_Point.Analyst);
            keyValuePairs.Add("$FluTemperature", water_Point.FluTemperature);
            keyValuePairs.Add("$WellAndWellNo", water_Point.WellAndWellNo);
            keyValuePairs.Add("$AirSource", water_Point.AirSource);
            keyValuePairs.Add("$Analytime", water_Point.Analytime);
            keyValuePairs.Add("$AnalyUnit", water_Point.AnalyUnit);
            keyValuePairs.Add("$TestLocation", water_Point.TestLocation);
            keyValuePairs.Add("$AmbientTemperature", water_Point.AmbientTemperature);
            keyValuePairs.Add("$Createtime", water_Point.Createtime);
            keyValuePairs.Add("$StepCurrent", water_Point.StepCurrent);
            keyValuePairs.Add("$InputUserId", water_Point.InputUserId);
            keyValuePairs.Add("$InputUserRealName", water_Point.InputUserRealName);

            string error = null;
            int count = ExecSqlCmd(sql, keyValuePairs, c =>
            {
                return c.ExecuteNonQuery();
            }, ex => { error = ex.Message; });
            return count > 0 ? new ResultSuccess("新增成功") : new Result("新增失败：" + error);
        }

        public IResult Check(Water_check_history history)
        {
            Snowflake snowflake = new Snowflake(1, 1);
            string sql = @$"
INSERT INTO water_check_history (
                                    Id,
                                    Check_user_name,
                                    Check_user_id,
                                    Check_time,
                                    Check_stat,
                                    Reject_reason,
                                    WaterPointId
                                )
                                VALUES (
                                    {snowflake.NextId()},
                                    $Check_user_name,
                                    $Check_user_id,
                                    $Check_time,
                                    $Check_stat,
                                    $Reject_reason,
                                    $WaterPointId
                                );  ";
            Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
            keyValuePairs.Add("$Check_user_name", history.Check_user_name);
            keyValuePairs.Add("$Check_user_id", history.Check_user_id);
            keyValuePairs.Add("$Check_time", history.Check_time);
            keyValuePairs.Add("$Check_stat", history.Check_stat);
            keyValuePairs.Add("$Reject_reason", history.Reject_reason);
            keyValuePairs.Add("$WaterPointId", history.WaterPointId);

            //主表修改状态
            if (history.Check_stat == 1)
            {
                //审核通过
                sql += "update  water_point  set  StepCurrent=4  where  id=" + history.WaterPointId + ";";
            }
            else
            {
                //驳回
                sql += "update  water_point  set  StepCurrent=3   where  id=" + history.WaterPointId + ";";
            }

            string error = null;
            int count = ExecSqlCmd(sql, keyValuePairs, c =>
             {
                 return c.ExecuteNonQuery();
             }, ex => { error = ex.Message; });
            if (count > 0)
            {
                return new ResultSuccess("审核保存成功");
            }
            return new Result("审核保存失败," + error);
        }

        public IResult Delete(long id)
        {
            string sql = $" update  Water_point  set  DeleteTime='{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}'  where id=" + id;
            string error = null;
            int count = ExecSqlCmd(sql, null, c =>
            {
                return c.ExecuteNonQuery();
            }, ex => { error = ex.Message; });
            return count > 0 ? new ResultSuccess("删除成功") : new Result("删除失败：" + error);
        }

        public IResult Edit(Water_point water_Point)
        {
            string sql = @$" UPDATE water_point
   SET
       Report_no = $Report_no,
       Client = $Client,
       Analyst = $Analyst,
       FluTemperature = $FluTemperature,
       WellAndWellNo = $WellAndWellNo,
       AirSource = $AirSource,
       Analytime = $Analytime,
       AnalyUnit = $AnalyUnit,
       TestLocation = $TestLocation,
       AmbientTemperature = $AmbientTemperature,
       Createtime = $Createtime,
       StepCurrent = $StepCurrent,
       InputUserId = $InputUserId,
       InputUserRealName = $InputUserRealName,
ProofreaderUserId=$ProofreaderUserId,
       Proofreader = $Proofreader,
       ProofreaderTime = $ProofreaderTime      
 WHERE    Id = " + water_Point.Id;

            Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
            keyValuePairs.Add("$Report_no", water_Point.Report_no);
            keyValuePairs.Add("$Client", water_Point.Client);
            keyValuePairs.Add("$Analyst", water_Point.Analyst);
            keyValuePairs.Add("$FluTemperature", water_Point.FluTemperature);
            keyValuePairs.Add("$WellAndWellNo", water_Point.WellAndWellNo);
            keyValuePairs.Add("$AirSource", water_Point.AirSource);
            keyValuePairs.Add("$Analytime", water_Point.Analytime);
            keyValuePairs.Add("$AnalyUnit", water_Point.AnalyUnit);
            keyValuePairs.Add("$TestLocation", water_Point.TestLocation);
            keyValuePairs.Add("$AmbientTemperature", water_Point.AmbientTemperature);
            keyValuePairs.Add("$Createtime", water_Point.Createtime);
            keyValuePairs.Add("$StepCurrent", water_Point.StepCurrent);
            keyValuePairs.Add("$InputUserId", water_Point.InputUserId);
            keyValuePairs.Add("$InputUserRealName", water_Point.InputUserRealName);
            keyValuePairs.Add("$Proofreader", water_Point.Proofreader);
            keyValuePairs.Add("$ProofreaderUserId", water_Point.ProofreaderUserId);
            keyValuePairs.Add("$ProofreaderTime", water_Point.ProofreaderTime);

            string error = null;
            int count = ExecSqlCmd(sql, keyValuePairs, c =>
            {
                return c.ExecuteNonQuery();
            }, ex => { error = ex.Message; });
            return count > 0 ? new ResultSuccess("修改成功") : new Result("修改失败：" + error);
        }

        public Water_point Get(long id)
        {
            string sql = @" select  *  
,(select  Check_user_name from water_check_history where WaterPointId=c.id  order by id desc limit 1) as check_user_name   
,(select Check_time            from water_check_history where WaterPointId=c.id  order by id desc limit 1) as check_time   
from Water_point as  c where  id=" + id;
            return base.ExecSqlCmd(sql, null, c =>
             {
                 var reader = c.ExecuteReader();
                 if (!reader.HasRows)
                 {
                     return null;
                 }
                 Water_point info = new Water_point();
                 if (reader.Read())
                 {
                     LoadFeild(reader, info);

                     //审核人
                     info.E3 = Convert.ToString(reader["check_user_name"]);

                     //审核时间
                     info.E4 = Convert.ToString(reader["check_time"]);
                 }
                 return info;
             });
        }

        private static void LoadFeild(System.Data.Common.DbDataReader reader, Water_point info)
        {
            info.Id = (long)reader["Id"].ToMyInt64();
            info.Report_no = reader["Report_no"].ToString();
            info.Client = (long)reader["Client"].ToMyInt64();
            info.Analyst = reader["Analyst"].ToMyInt64();
            info.FluTemperature = reader["FluTemperature"].ToMyDecimal();
            info.WellAndWellNo = reader["WellAndWellNo"].ToString();
            info.AirSource = reader["AirSource"].ToString();
            info.Analytime = reader["Analytime"].ToString();
            info.AnalyUnit = (long)reader["AnalyUnit"].ToMyInt64();
            info.TestLocation = reader["TestLocation"].ToString();
            info.AmbientTemperature = reader["AmbientTemperature"].ToMyDecimal();
            info.Createtime = reader["Createtime"].ToString();
            info.StepCurrent = (byte)reader["StepCurrent"].ToMyInt64();
            info.InputUserId = (long)reader["InputUserId"].ToMyInt64();
            info.InputUserRealName = reader["InputUserRealName"].ToString();
            info.Proofreader = reader["Proofreader"].ToString();
            info.ProofreaderTime = reader["ProofreaderTime"].ToString();

            //校对人id。添加时间：2023-1-9 00:47:03
            info.ProofreaderUserId = reader["ProofreaderUserId"].ToMyInt64();

            info.DeleteTime = reader["DeleteTime"].ToString();
        }

        public PageModel<Water_point> Page(Water_point where, int p, int rows)
        {
            Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
            PageModel<Water_point> pageModel = new PageModel<Water_point>();
            pageModel.PageIndex = p;
            pageModel.PageSize = rows;

            StringBuilder whereSb = new StringBuilder();
            if (where != null)
            {
                //报告编号
                if (!string.IsNullOrWhiteSpace(where.Report_no))
                {
                    whereSb.AppendLine("  and  Report_no   like  $Report_no ");
                    keyValuePairs.Add("$Report_no", "%" + where.Report_no + "%");
                }
                if (!string.IsNullOrWhiteSpace(where.E3) && DateTime.TryParse(where.E3, out DateTime dd1))
                {
                    whereSb.AppendLine($"  and  Createtime>'{dd1.AddDays(-1).ToString("yyyy-MM-dd")}' ");
                }
                if (!string.IsNullOrWhiteSpace(where.E4) && DateTime.TryParse(where.E4, out DateTime dd2))
                {
                    whereSb.AppendLine($"  and  Createtime<'{dd2.AddDays(1).ToString("yyyy-MM-dd")}' ");
                }
                //步骤值查询 //添加时间：2022-12-29 21:04:12
                if (where.WorkList?.Count > 0)
                {
                    List<string> stepList = new List<string>();
                    foreach (var item in where.WorkList)
                    {
                        stepList.Add($"  StepCurrent={item} ");
                    }
                    string step = $"  and  ({ string.Join(" or  ", stepList)  })  ";
                    whereSb.AppendLine(step);
                }
            }
            //查询总记录数
            string sqlTotal = $"select count(0)  from  water_point  where  DeleteTime is null  {whereSb.ToString() } ";
            pageModel.Total = ExecSqlCmd(sqlTotal, keyValuePairs, c =>
            {
                var obj = c.ExecuteScalar();
                return (int)obj.ToMyInt64();
            });
            string sql = @$"  select  *  
,(select  Check_user_name from water_check_history where WaterPointId=c.id  order by id desc limit 1) as check_user_name   
,(select Check_time            from water_check_history where WaterPointId=c.id  order by id desc limit 1) as check_time   
from   water_point  as  c  
where  DeleteTime is null  {whereSb.ToString() }  order by Report_no desc  limit   {rows}  offset  {(p - 1) * rows}  ";
           //客户要根据样品编号排序，大的排上面

            pageModel.List = ExecSqlCmd(sql, keyValuePairs, c =>
            {
                var reader = c.ExecuteReader();
                if (!reader.HasRows)
                {
                    return null;
                }
                List<Water_point> list = new List<Water_point>();
                while (reader.Read())
                {
                    Water_point info = new Water_point();
                    LoadFeild(reader, info);
                    info.E3 = reader["check_user_name"].ToString();//审核人
                    info.E4 = reader["check_time"].ToString();//审核时间
                    list.Add(info);
                }
                return list;
            });
            return pageModel;
        }

        /// <summary>
        /// 水露点，统计数量，审核通过的，没有被删除的
        /// </summary>
        /// <returns></returns>
        /// 创建时间：2023-1-3 09:39:48。作者：王浩力
        public int GetCount()
        {
            string sql = @$" SELECT  count(1)  FROM  water_point  where    StepCurrent = 4  and  DeleteTime is null ";
            return ExecSqlCmd(sql, null, c =>
            {
                long va = (long)c.ExecuteScalar().ToMyInt64();
                return (int)va;
            });
        }

    }
}
